package org.lds.message.center.aliyun.starter;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.lds.message.center.aliyun.constant.AliyunSmsConstant;
import org.lds.message.center.common.constant.CommonConstant;
import org.lds.message.center.common.util.ScheduledUtil;
import org.lds.message.center.plugin.core.remote.RemoteService;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;

import java.net.InetAddress;
import java.net.UnknownHostException;

@Slf4j
@RequiredArgsConstructor
public class AliyunSmsRegisterAdmin implements ApplicationRunner {
    private final RemoteService remoteService;
    @Override
    public void run(ApplicationArguments args) throws Exception {
        String healthUrl = getHealthUrl();
        ScheduledUtil.defaultSyncClosableScheduled(() -> {
            remoteService.registerChannel(AliyunSmsConstant.CHANNEL_TYPE, AliyunSmsConstant.CHANNEL_NAME, "阿里云短信通道", healthUrl);
            log.info("阿里云短信通道注册成功. type={} name={}", AliyunSmsConstant.CHANNEL_TYPE, AliyunSmsConstant.CHANNEL_NAME);
        });
    }

    private String getHealthUrl() throws UnknownHostException {
        InetAddress addr = InetAddress.getLocalHost();
        return "http://" +
                addr.getHostAddress() + ":" +
                remoteService.getRemoteProperties().getLocalPort() +
                "/" + AliyunSmsConstant.CHANNEL_TYPE + "/" + AliyunSmsConstant.CHANNEL_NAME + CommonConstant.HEALTH;
    }
}
